<script setup lang='ts' name="approval-acceptance">
import type { FormRules } from 'element-plus'

import { useApplyAcceptance, useJcDeliveryNoteGetOne } from '@fl/api/supplier'
import { SearchTable } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { cloneDeep } from 'lodash-es'

import { useTable } from './hooks/use-table'

const visible = defineModel<boolean>('visible')
const id = defineModel<string>('id')
const { data, isLoading } = useJcDeliveryNoteGetOne(id)

const { isPending, mutate } = useApplyAcceptance()

const tableList = ref<any>([])

const attachmentUrlList = ref<any>([])

const acceptanceAttachList = ref<any>([])

const state = { acceptanceAttach: [], acceptanceDate: '', acceptanceRemark: '' }
const form = ref<any>({ ...state })

const formRef = ref()
const tableRef = ref()

const rules = reactive<FormRules<any>>({
    acceptanceAttach: [
        { message: '请上传验货单附件', required: true, trigger: 'blur' },
    ],
    acceptanceDate: [
        { message: '请选择验收时间', required: true, trigger: 'blur' },
    ],
    acceptanceRemark: [
        { message: '请输入验收说明', required: true, trigger: 'blur' },
    ],
})

const { gridOptions } = useTable()

const isEdit = computed(() => {
    return data.value?.deliveryNoteState === 1 || data.value?.deliveryNoteState === 5
})

const title = computed(() => data.value?.deliveryNoteState === 1 ? '申请验收' : '详情')

async function submit() {
    const valid = await formRef.value.validate()
    if (valid) {
        const acceptanceAttach = form.value.acceptanceAttach.map((item: any) => item.url)
        const params = {
            ...form.value,
            acceptanceAttach: JSON.stringify(acceptanceAttach),
            id: id.value,
            products: tableList.value,
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function showFile(file: any) {
    if (file) {
        window.open(file)
    }
}

function cancel() {
    visible.value = false
}
function reset() {
    id.value = ''
}
watchEffect(() => {
    if (data.value) {
        tableList.value = cloneDeep(data.value?.products ?? [])
        attachmentUrlList.value = data.value?.attachmentUrl ? JSON.parse(data.value?.attachmentUrl) : []
        acceptanceAttachList.value = data.value?.acceptanceAttach ? JSON.parse(data.value?.acceptanceAttach) : []
    }
})
</script>

<template>
    <el-dialog v-model="visible"
               width="1000"
               :close-on-click-modal="false"
               :title="title"
               align-center
               @close="cancel"
               @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    :rows="5"
        />

        <template v-else>
            <div class="info-title">
                发货信息
            </div>

            <el-form label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="预计发货时间:">
                            {{ data?.estimatedShippingDate }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="发货说明:">
                            {{ data?.shippingInstructions }}
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="物流公司:">
                            {{ data?.logisticsCompany }}
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="物流单号:">
                            {{ data?.trackingNumber }}
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="发货单附件:">
                            <ul class="w-full">
                                <li v-for="item in attachmentUrlList"
                                    :key="item"
                                    class="truncate underline underline-offset-1 w-full cursor-pointer"
                                    :title="item"
                                    @click="showFile(item)"
                                >
                                    {{ item }}
                                </li>
                            </ul>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div class="info-title">
                商品信息
            </div>

            <SearchTable v-bind="gridOptions"
                         ref="tableRef"
                         :data="tableList"
            >
                <template #quantityAccepted="{ row }">
                    <el-input-number v-if="isEdit"
                                     v-model="row.quantityAccepted"
                                     style="width: 100px;"
                                     :precision="0"
                                     :min="1"
                                     :max="row.quantityShipped"
                                     size="small"
                    />

                    <span v-else>{{ row.quantityAccepted }}</span>
                </template>
            </SearchTable>

            <div class="info-title">
                验收信息
            </div>

            <el-form ref="formRef"
                     :model="form"
                     :rules="rules"
                     label-width="auto"
            >
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="验收时间"
                                      :prop="isEdit ? 'acceptanceDate' : ''"
                        >
                            <el-date-picker v-if="isEdit"
                                            v-model="form.acceptanceDate"
                                            type="date"
                                            value-format="YYYY-MM-DD"
                            />

                            <span v-else>{{ data?.acceptanceDate }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="验收单附件"
                                      :prop="isEdit ? 'acceptanceAttach' : ''"
                        >
                            <FlUpload v-if="isEdit"
                                      v-model="form.acceptanceAttach"
                                      :limit="10"
                                      list-type="text"
                                      accept=".png,.jpg,.jpeg,.docx,.xlsx,.pdf"
                                      tips
                            />

                            <ul v-else
                                class="w-full"
                            >
                                <li v-for="item in acceptanceAttachList"
                                    :key="item"
                                    class="truncate underline underline-offset-1 w-full cursor-pointer"
                                    :title="item"
                                    @click="showFile(item)"
                                >
                                    {{ item }}
                                </li>
                            </ul>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="验收说明"
                                      :prop="isEdit ? 'acceptanceRemark' : ''"
                        >
                            <el-input v-if="isEdit"
                                      v-model="form.acceptanceRemark"
                            />

                            <span v-else>{{ data?.acceptanceRemark }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div style="text-align: center;margin-top: 10px;">
                <el-button @click="cancel">
                    关闭
                </el-button>

                <el-button v-if="isEdit"
                           type="primary"
                           :loading="isPending"
                           @click="submit"
                >
                    申请验收
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 40px;
}
</style>
